﻿using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using Marmat.Foundation;
using Marmat.FrameWork;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Marmat.Template.WinForm
{
    /// <summary>
    /// 多级菜单的主窗体实现
    /// </summary>
    public partial class MainMultilevelForm : Marmat.Forms.Skin.Form, IMainForm
    {
        private readonly IMeunManagement meunService;
        private WebClient webclient;

        /// <summary>
        /// 构建窗体实例。
        /// </summary>
        protected MainMultilevelForm() : this(null)
        {
        }

        /// <summary>
        /// 构建窗体实例。
        /// </summary>
        /// <param name="meunService"></param>
        public MainMultilevelForm(IMeunManagement meunService)
        {
            this.meunService = meunService;
            InitializeComponent();
            Marmat.Foundation.IProvider provider = null;
            var upgrade = SystemCommand.GetService<IUpgrade>();
            if (upgrade != null)
            {
                var button = new ToolStripMenuItem();
                button.Text = "检查更新";
                button.Name = "update";
                this.contextMenuStrip1.Items.Add(button);
            }
        }

        private void MainMultilevelForm_Load(object sender, EventArgs e)
        {
            if (this.meunService != null)
            {
                List<IMenu> menus = meunService.ToList();
                this.BuildMenu(menus);
            }
        }

        public Image Logo
        {
            set
            {
                this.topMenu1.Logo = value;
            }
        }

        public string NickName { get; set; }


        string IMainForm.SelectedFormName
        {
            get => this.tabPanelControl1.SelectedForm?.Name;
            set => this.tabPanelControl1.SelectedForm = this.tabPanelControl1.Forms.FirstOrDefault(item => item.Name == value);
        }

        public Form[] Forms => this.tabPanelControl1.Forms;

        void IMainForm.AddForm(Form form)
        {
            this.tabPanelControl1.AddForm(form);
        }

        bool IMainForm.ContainsForm(string name)
        {
            return this.tabPanelControl1.ContainsForm(name);
        }

        /// <summary>
        /// 生成菜单
        /// </summary>
        /// <param name="menus"></param>
        private void BuildMenu(List<IMenu> menus)
        {
            if (webclient is null)
            {
                webclient = new WebClient();
                webclient.DownloadDataCompleted += this.Webclient_DownloadDataCompleted;
            }
            var items = menus.Where(x => string.IsNullOrEmpty(x.Parent)).ToList();
            var menuItems = new List<TopMenuItem>();
            foreach (var item in items)
            {
                var topMenu = new TopMenuItem();
                topMenu.Caption = item.Text;

                if (!string.IsNullOrEmpty(item.Uri))
                {
                    Action<Image> action = (Image img) => topMenu.Image = img;
                    webclient.DownloadDataAsync(new Uri(item.Uri), action);
                }
                topMenu.Name = item.Name;
                menuItems.Add(topMenu);
            }
            if (menuItems.Count > 0)
            {
                this.topMenu1.AddControl(menuItems);
                this.topMenu1_MenuItemClick(menuItems.First());
            }
        }

        private void Webclient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            Action action = () =>
            {
                using (MemoryStream ms = new MemoryStream(e.Result))
                {
                    Image img = Image.FromStream(ms);//生成图片
                    if (e.UserState is Action<Image> action)
                        action.Invoke(img);
                }
            };
            this.Invoke(action);
        }

        private void topMenu1_MenuItemClick(TopMenuItem menuItem)
        {
            if (this.meunService != null)
            {
                List<IMenu> menus = meunService.ToList();
                menus.RemoveAll(x => x.Parent == null);
                var items = menus.Where(x => x.Parent == menuItem.Name).ToList();
                var leftMenuItems = new List<LeftMenuItem>();
                foreach (var item in items)
                {
                    var leftMenuParent = new LeftMenuItem
                    {
                        Name = item.Name,
                        Caption = item.Text,
                        Sequnce = item.Sequnce,
                        Tag = item,
                    };

                    if (!string.IsNullOrEmpty(item.Uri))
                    {
                        Action<Image> action = (Image img) => leftMenuParent.Icon = img;
                        webclient.DownloadDataAsync(new Uri(item.Uri), action);
                    }

                    var _menu = menus.Where(x => x.Parent == item.Name).ToArray();
                    foreach (var _item in _menu)
                    {
                        var leftMenu = new LeftMenuItem(leftMenuParent)
                        {
                            Name = _item.Name,
                            Caption = _item.Text,
                            Tag = _item
                        };

                        if (!string.IsNullOrEmpty(_item.Uri))
                        {
                            Action<Image> action = (Image img) => leftMenu.Icon = img;
                            webclient.DownloadDataAsync(new Uri(item.Uri), action);
                        }
                        leftMenuParent.Children.Add(leftMenu);
                    }
                    leftMenuItems.Add(leftMenuParent);

                }
                this.leftMenu1.CoverControls(leftMenuItems.ToArray());
            }
        }

        private void leftMenu1_MenuItemClick(LeftMenuItem menuItem)
        {
            if (menuItem.Tag is IMenu menu)
                this.meunService?.ItemClick(menu);

        }

        private void MainMultilevelForm_FormButtonItemClick(object Sender, Marmat.Forms.Skin.FormButtonClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "设置":
                    var point = new Point(e.ClientRectangle.X - 8, e.ClientRectangle.Y - 8);
                    this.contextMenuStrip1.Show(this, point);
                    break;
            }
        }

        /// <summary>
        /// 注册设置按钮的子项
        /// </summary>
        public void SettingRegisterItems(params ToolStripMenuItem[] items)
        {
            this.contextMenuStrip1.Items.AddRange(items);
        }

        private void ContextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "update":
                    var upgrade = SystemCommand.GetService<IUpgrade>();
                    if (upgrade.CheckUpgrade())
                    {
                        if (MessageBox.Show("您的软件有新的版本，是否更新？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                            upgrade.Upgrade();
                    }
                    else
                        MessageBox.Show("您的软件已是最新版本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
        }

        private void MainMultilevelForm_DrawFormButton(object sender, Marmat.Forms.Skin.DrawFormButtonEventArgs e)
        {
            if (e.Item.Name == "welcome")
            {
                var font = new Font("微软雅黑", 10.5F, FontStyle.Bold, GraphicsUnit.Point);
                var format = new StringFormat();
                format.FormatFlags = StringFormatFlags.NoClip;
                format.Alignment = StringAlignment.Far;
                using (Brush brush = new SolidBrush(Color.White))
                {
                    string text;
                    if (string.IsNullOrEmpty(this.NickName)) text = "欢迎回来！";
                    else text = "欢迎回来，" + this.NickName;
                    e.Graphics.DrawString(text, font, brush, e.ClipRectangle, format);
                }
            }
        }

        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        if (Environment.OSVersion.Version.Major >= 6)
        //        {
        //            // Vista以上       
        //            CreateParams cp = base.CreateParams;
        //            cp.ExStyle |= 0x02000000;
        //            return cp;
        //        }
        //        else
        //        {
        //            return base.CreateParams;
        //        }
        //    }
        //}

    }
}
